<?php
    class UserController {
        private static
            $view;
        private
            $hasErrors = 0,
            $responses = array();
        const
            EMPTY_EMAIL = 'Empty e-mail.',
            EMPTY_PASSWORD = 'Empty password.',
            NOT_MATCH_CONFIRM_PASSWORD = 'No confirm password.';
        function __construct(){
            if (empty(self::$view)){
                self::$view = new UserView;
            }
        }
        function getResponses(){
            return $this->responses;
        }
        function insert(){
            if (empty($_POST['email'])){
                $this->responses[] = self::EMPTY_EMAIL;
                $this->hasErrors = 1;
            }
            if (empty($_POST['password'])){
                $this->responses[] = self::EMPTY_PASSWORD;
                $this->hasErrors = 1;
            }
            if ($this->hasErrors){
                self::$view->render($this->responses);
            } else {
                $user = new UserModel(
                    array(
                        'email' => mysql_real_escape_string($_POST['email']),
                        'password' => mysql_real_escape_string($_POST['password'])
                    )
                );
                $userMapper = new UserMapper;
                $userMapper->insert($user);
                $this->responses = array_merge(
                    $this->responses,
                    $userMapper->getResponses()
                );
                self::$view->render($this->responses);
            }
        }
        function auth(){
            $userMapper = new UserMapper;
            self::$view->render($userMapper->getCurrentUser());
        }
        function logOut(){
            $userMapper = new UserMapper;
            $userMapper->logOut();
            self::$view->render($userMapper->getResponses());
        }
        function logIn(){
            if (empty($_POST['email'])){
                $this->responses[] = self::EMPTY_EMAIL;
                $this->hasErrors = 1;
            }
            if (empty($_POST['password'])){
                $this->responses[] = self::EMPTY_PASSWORD;
                $this->hasErrors = 1;
            }
            if ($this->hasErrors){
                self::$view->render($this->responses);
            } else {
                $user = new UserModel(
                    array(
                        'email' => mysql_real_escape_string($_POST['email']),
                        'password' => mysql_real_escape_string($_POST['password'])
                    )
                );
                $userMapper = new UserMapper();
                $userMapper->logIn($user);
                self::$view->render($userMapper->getResponses());
            }
        }
    }
?>
        